export default class Input {
    //最后的键盘按键
    public static boardKey: string | null
    //最后的鼠标按键
    public static mouseKey: number | null

    //所有键盘按键容器
    public static boardKeys: string[] = []
    //所有鼠标按键容器
    public static mouseKeys: string[] = []

    //水平方向，左-1右1 停止为0
    public static Horizontal: 1 | -1 | 0 = 0
    //竖直方向，上-1下1 停止为0
    public static Vertical: 1 | -1 | 0 = 0

    //方向按键  可以自定义
    public static H_Left = "a"
    public static H_Right = "d"
    public static H_Top = "w"
    public static H_bottom = "s"

    static {

        window.addEventListener("keydown", (ev: KeyboardEvent) => {
            Input.boardKey = ev.key
            if (Input.boardKeys.includes(ev.key)) return

            Input.boardKeys.push(ev.key)
            Input.reSetDirection()
        })
        window.addEventListener("keyup", (ev: KeyboardEvent) => {
            //键盘按键容器中移除
            let index = Input.boardKeys.indexOf(ev.key)
            if (index != -1) {
                Input.boardKeys.splice(index, 1)
            }
            //判断是否还有键被按下
            if(Input.boardKeys.length>0) {
                Input.boardKey = Input.boardKeys[Input.boardKeys.length-1]
            }else{
                Input.boardKey = null
            }
            Input.reSetDirection()
        })
        window.addEventListener("mousedown", (ev: MouseEvent) => {
            Input.mouseKey = ev.button
        })
        window.addEventListener("mouseup", (ev: MouseEvent) => {
            Input.mouseKey = null
        })


    }
    private static reSetDirection() {
        //Horizontal
        if (Input.boardKeys.includes(Input.H_Left)) {
            if (Input.Horizontal != -1) Input.Horizontal += -1
        }else if (Input.boardKeys.includes(Input.H_Right)) {
            if (Input.Horizontal != 1) Input.Horizontal += 1
        }else{
            Input.Horizontal =0
        }
        //Vertical
        if (Input.boardKeys.includes(Input.H_Top)) {
            if (Input.Vertical != -1) Input.Vertical += -1
        }else if (Input.boardKeys.includes(Input.H_bottom)) {
            if (Input.Vertical != 1) Input.Vertical += +1
        }else {
            Input.Vertical = 0
        }

    }
}